package com.hhf.feiojjudgeservice.codesandbox.factory;


import com.hhf.feiojcommonservice.common.ErrorCode;
import com.hhf.feiojcommonservice.exception.BusinessException;
import com.hhf.feiojjudgeservice.codesandbox.CodeSandbox;
import com.hhf.feiojjudgeservice.codesandbox.impl.ExampleCodeSandbox;
import com.hhf.feiojjudgeservice.codesandbox.impl.RemoteCodeSandbox;
import com.hhf.feiojjudgeservice.codesandbox.impl.ThirdPartyCodeSandbox;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author hhf
 * @Date 2024/10/27
 * @Description 单例工厂(懒汉式加载)
 */
public class CodeSandboxFactory {

    private static Map<String, CodeSandbox> codeSandboxMap = new HashMap<>();

    public static CodeSandbox getInstance(String type) {

        //从map中获取实例
        CodeSandbox codeSandbox = codeSandboxMap.get(type);
        //若不存在,则创建后再加入
        if (codeSandbox == null) {
            synchronized (CodeSandboxFactory.class) {
                codeSandbox = codeSandboxMap.get(type);
                if (codeSandbox == null) {
                    CodeSandbox codeSandboxImpl = selectCodeSandbox(type);
                    codeSandboxMap.put(type,codeSandboxImpl);
                    return codeSandboxImpl;
                }
            }
        }
        //获取
        return codeSandbox;
    }

    private static CodeSandbox selectCodeSandbox(String type) {
        switch (type){
            case "example":
                return new ExampleCodeSandbox();
            case "remote":
                return new RemoteCodeSandbox();
            case "thirdParty":
                return new ThirdPartyCodeSandbox();
            default:
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"无该类型的代码沙盒");
        }
    }
}
